/*
 * Author : Yuval Kovler 2011
 * 
 */


package implementation.DB;

import implementation.DB.DBreverse.Follow;
import implementation.DB.DBreverse.Forum;
import implementation.DB.DBreverse.Forumproperties;
import implementation.DB.DBreverse.Post;
import implementation.DB.DBreverse.User;
import implementation.DB.readOnlyRecords.CReadOnlyForum;
import implementation.DB.readOnlyRecords.CReadOnlyPost;
import implementation.DB.readOnlyRecords.CReadOnlyThread;
import implementation.DB.readOnlyRecords.CReadOnlyUser;
import implementation.logger.CLoggerFactory;
import implementation.server.IDB;
import implementation.server.IReadOnlyForum;
import implementation.server.IReadOnlyPost;
import implementation.server.IReadOnlyThread;
import implementation.server.IReadOnlyUser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;



//////// catch java.lang.NullPointerException ??????
////session.close();

public class CDataBase implements IDB{
	
	private static Logger Log;
	private static SessionFactory sessionFactory;
	private int idCounter;

	
	public CDataBase (){
		
		try {
			Log = CLoggerFactory.getFileLogger("DBLogger","C:/MaldaForumLogs/DB-Log.txt");
		} catch (IOException e) {
			System.out.println(" ERROR!!!!!!! - Initial Log creation failed : " +e);
		}
		
		try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
        	Log.debug("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }

        
        
        idCounter=1;
        idCounter=retriveIdFromDB();
        if ( idCounter==-1 || idCounter == 0){
        	idCounter=1;	
		
			//Initialization
			
	        addUser("a","a");
			addUser("maxim", "123456");
			addUser("yuri", "123456");
			addUser("yuval", "123456");
			addUser("raz", "123456");
			
			follow(getUserID("maxim"),getUserID("raz"));
			follow(getUserID("maxim"), getUserID("yuval"));
			follow(getUserID("yuval"), getUserID("yuri"));
			follow(getUserID("raz"), getUserID("yuri"));
			
			
			int firstfourmId=addForum("Forum 1");
			int secondfourmId=addForum("Forum 2");
			int thirdfourmId=addForum("Forum 3");
			addForum("Forum 4");
			addForum("Forum 5");
			addForum("Forum 6");
			addForum("Forum 7");
			addForum("Forum 8");
			addForum("Forum 9");
			addForum("Forum 10");
			addForum("Forum 11");
			addForum("Forum 12");
			addForum("Forum 13");
			addForum("Forum 14");
			addForum("Forum 15");	
			
			
			int threadId=addThread(firstfourmId, "Maccabi", "Tel Aviv",getUserID("yuval"));
			addPost(threadId, "Yes", "yes", getUserID("yuval"));
			addPost(threadId, "No", "yes", getUserID("yuval"));
			addPost(threadId, "Maybe", "yes", getUserID("yuval"));
			addPost(threadId, "YesNo", "yes", getUserID("yuval"));/**/
        	
        	
        }
		
	}

	@Override
	public int addUser(String username, String password) {		
		
		User user=new User();
		
		try{
			Session session = sessionFactory.openSession();	
			DBSessionManager manager = new DBSessionManager(session);
			
			//write changes here
			user.setUserName(username);
			user.setPassword(password);
			user.setDeleted(false);
			user.setModerator(false);
			user.setUserId(idCounter);
			idCounter++;
			updateIDInDB();
			
			session.beginTransaction();
			
			//write the actions to do		
			manager.save(user);
			
			session.getTransaction().commit();
			session.flush();
			session.close();
			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
		 	}		
		 
		 Log.info("Added User with Username :" +username + " User id: " +user.getUserId());

		 return user.getUserId();
	}

	@Override
	public int addForum(String forumName) {
							
		Forum forum=new Forum();
		
		try{
		
		Session session = sessionFactory.openSession();	
		DBSessionManager manager = new DBSessionManager(session);
		
		//write changes here
		forum.setForumName(forumName);
		forum.setDeleted(false);
		forum.setForumId(idCounter);
		idCounter++;
		updateIDInDB();
		
		session.beginTransaction();
		
		//write the actions to do		
		manager.save(forum);
		
		session.getTransaction().commit();
		session.flush();
		session.close();
			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is in addForum: " +e.getMessage());
			 return -1;
		 	}		
		 
		 Log.info("Added Forum with name :" + forumName + " Forum id: " + forum.getForumId());
	
		 return forum.getForumId();
	}

	@Override
	public int addThread(int forumId, String threadTopic, String threadContent,
			int authorID) {
		
		implementation.DB.DBreverse.Thread Thread=new implementation.DB.DBreverse.Thread();
		
		try{		
			Session session = sessionFactory.openSession();	
			DBSessionManager manager = new DBSessionManager(session);
			
			//write changes here
			
			Forum forum=new Forum();
			forum.setForumId(forumId);
						
			User user=new User();
			user.setUserId(authorID);
			
			Thread.setForum(forum);
			Thread.setThreadTopic(threadTopic);
			Thread.setThreadContent(threadContent);
			Thread.setUser(user);
			Thread.setDeleted(false);
			Thread.setThreadId(idCounter);
			idCounter++;
			updateIDInDB();
			
			session.beginTransaction();
			
			//write the actions to do		
			manager.save(Thread);
			
			session.getTransaction().commit();
			session.flush();
			session.close();
				 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
		 	}		
		 
		 Log.info("Added Thread to forum id : " + forumId 
				 +" with topic :" + threadTopic 
				 +" thread id : "+ Thread.getThreadId());
		 
		 return Thread.getThreadId();
	}

	@Override
	public int addPost(int threadID, String postTopic, String postcontent,
			int authorID) {
		
		
	
		//write changes here
		
		implementation.DB.DBreverse.Thread thread=new implementation.DB.DBreverse.Thread();
		thread.setThreadId(threadID);
		
		User user=new User();
		user.setUserId(authorID);
		
		Post post=new Post();
		post.setThread(thread);
		post.setPostTopic(postTopic);
		post.setPostContent(postcontent);
		post.setUser(user);
		post.setDeleted(false);
		post.setPostId(idCounter);
		idCounter++;
		updateIDInDB();
		
		try{
			Session session = sessionFactory.openSession();	
			DBSessionManager manager = new DBSessionManager(session);
			
		session.beginTransaction();
		
		//write the actions to do		
		manager.save(post);
		
		session.getTransaction().commit();
		session.flush();
		session.close();
			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
		 	}		
		 
		 Log.info("Added Post to thread id : " + threadID 
				 + " with topic :" + postTopic
				 + " post id :" + post.getPostId() );
		 
		 return post.getPostId();
	
	}

	@Override
	public IReadOnlyUser getUser(int userId) {
		
		Log.debug("Getting User with id :" +userId);

		User user=null;
 		
		Session session = sessionFactory.openSession();
	
		Query query = session.createQuery("from User as u where u.userId = " + userId);
		
		try{
		
			@SuppressWarnings("unchecked")
			java.util.List<User> list = query.list();	
			Iterator<User> it=list.iterator();
			
			if (it.hasNext())
				user=it.next();
			;
			
		 	}		
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
	 	}
		 

		ArrayList<Integer> tFollower= getFollowers(userId);;
		

		ArrayList<Integer> tFollowed= getFollowees(userId);;
		
		/*
		Iterator<Follower> tFolloweeIterator=user.getFollowersForFolloweeId().iterator();
		while(tFolloweeIterator.hasNext()){
			tFollowee.add(tFolloweeIterator.next().getUserByFolloweeId().getUserId());
		}
		*/
		
		CReadOnlyUser userRecord=new CReadOnlyUser( userId , user.getUserName() ,
													user.getPassword(),   tFollower , tFollowed );
		
		
		session.close();
		Log.info("Retrived a user with id : " + userId + " username: " + user.getUserName());
		return userRecord;
	}
	
	@Override
	public int getUserID(String username) {
		Log.debug("Getting User id with username :" +username);
	
		User user=new User();

		
		Session session = sessionFactory.openSession();
	
		Query query = session.createQuery("from User as u where u.userName = " + "'" + username + "'");
	
	
		try{
			@SuppressWarnings("unchecked")
			java.util.List<User> list = query.list();	
			Iterator<User> it=list.iterator();
			
			if (it.hasNext())
				user=it.next();	
			else return -1;
			
		 	}			
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
	 	}
		session.close();
	
		Log.info("Retrived a user id with username : " + username + " id is: " + user.getUserId());
		return user.getUserId();
	}

	@Override
	public IReadOnlyForum getForum(int forumId) {
	
		Log.debug("Trying to get a forum with id : " +forumId);
		
		Forum forum=new Forum();
	
		
			Session session = sessionFactory.openSession();
			
			Query query = session.createQuery("	from Forum as f " +
											  "	where f.forumId = " + forumId +
											  " and f.deleted=false ");			
			
			
		try{	
			@SuppressWarnings("unchecked")
			java.util.List<Forum> list = query.list();
			Iterator<Forum> it=list.iterator();
			
			forum=it.next();			
		} catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return null;
		 	}
		
			
		CReadOnlyForum forumRecord=new CReadOnlyForum(forumId, forum.getForumName());
		
		Iterator<implementation.DB.DBreverse.Thread> threadIterator=forum.getThreads().iterator();
		implementation.DB.DBreverse.Thread Thread;
		while(threadIterator.hasNext()){
			Thread=threadIterator.next();
			if (!Thread.getDeleted())
			forumRecord.addThread(Thread.getThreadId());
		}
		
		session.close();
		Log.info("Retrived a forum with id : " + forumId + " Forum Name: " + forum.getForumName());
			
		return	forumRecord;
	}

	@Override
	public ArrayList<IReadOnlyForum> getForums() {
	
		Log.debug("Trying to get all forums");	
		
		ArrayList<IReadOnlyForum> forums=new ArrayList<IReadOnlyForum>();
		Forum forum=new Forum();
		CReadOnlyForum forumRecord;
		
		
		Session session = sessionFactory.openSession();
		
		Query query = session.createQuery("	from Forum as f where f.deleted = false" );		 
		
	
		//Query query = session.createQuery("	from Forum as f where f.deleted = 1" );		 
	
		try{
			@SuppressWarnings("unchecked")
			java.util.List<Forum> list = query.list();	
			Iterator<Forum> it=list.iterator();
			implementation.DB.DBreverse.Thread Thread=new implementation.DB.DBreverse.Thread();
			
			while(it.hasNext()){
				forum=it.next();
				//checking if the forum has not been deleted
				if (!forum.getDeleted()){
					
					forumRecord=new CReadOnlyForum(forum.getForumId(), forum.getForumName());
					Iterator<implementation.DB.DBreverse.Thread> threadIterator=forum.getThreads().iterator();
					
					//copying all the threads
					while(threadIterator.hasNext()){						
						Thread=threadIterator.next();
						//checking if the thread has not been deleted
						if (!forum.getDeleted()){
							forumRecord.addThread(Thread.getThreadId());
						}
					}
					
					forums.add(forumRecord);
				}
			}
			
		} catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return null;
		 	}
		
		session.close();
		Log.info("Retrived all forums , number of forums: " + forums.size());
			
		return	forums;
		
	}

	@Override
	public IReadOnlyThread getThread(int threadID) {
	
		Log.debug("Trying to get a thread with id : " +threadID);
		
		implementation.DB.DBreverse.Thread Thread=new implementation.DB.DBreverse.Thread();
		
		
		Session session = sessionFactory.openSession();
		
		Query query = session.createQuery("	from Thread as t " +
										  "	where t.threadId = " + threadID +
										  " and t.deleted = false ");		 
	
		try{
			@SuppressWarnings("unchecked")
			java.util.List<implementation.DB.DBreverse.Thread> list = query.list();	
			Iterator<implementation.DB.DBreverse.Thread> it=list.iterator();
			
			Thread=it.next();
		} catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return null;
		}
			
		CReadOnlyThread threadRecord = new CReadOnlyThread(threadID, Thread.getThreadTopic() 
														, Thread.getThreadContent() , Thread.getUser().getUserId()
														, Thread.getForum().getForumId());
		
		Iterator<Post> postIterator=Thread.getPosts().iterator();
		while(postIterator.hasNext()){
			threadRecord.addPost(postIterator.next().getPostId());
		}
		
		session.close();
		Log.info("Retrived a thread with id : " + threadID + " threadID topic: " + Thread.getThreadTopic());
			
		return	threadRecord;
	}

	@Override
	public IReadOnlyPost getPost(int postId) {
		Log.debug("Trying to get a post with id : " +postId);
		
		Post post=new Post();		
		
		Session session = sessionFactory.openSession();
		
		Query query = session.createQuery("	from Post as p " +
										  "	where p.postId = " + postId +
										  " and p.deleted = false ");		 
	
		try{
			@SuppressWarnings("unchecked")
			java.util.List<Post> list = query.list();	
			Iterator<Post> it=list.iterator();
			
			post=it.next();
		} catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return null;
		 	}
		
			
		CReadOnlyPost postRecord=	new CReadOnlyPost(post.getPostId(), post.getPostTopic(),
														post.getPostContent(), post.getUser().getUserId()
															,post.getThread().getThreadId()
																,post.getThread().getForum().getForumId());
		
		session.close();
		Log.info("Retrived a post with id : " + postId + " post topic: " + post.getPostTopic());
			
		return	postRecord;
	
	}

	@Override
	public boolean follow(int FollowerID, int followedID) {
		//check if they aren't already friends...
		
		Log.info("Added a friendship of users with ids  :" +FollowerID + ", " +followedID);

		Follow follower=new Follow();
		try{
		
			Session session = sessionFactory.openSession();	
			DBSessionManager manager = new DBSessionManager(session);

			follower.setFollowedId(followedID);
			follower.setFollowerId(FollowerID);
			

			session.beginTransaction();
			
			//write the actions to do		
			manager.save(follower);
			//manager.save(SecondFriend);
			
		session.getTransaction().commit();
		session.flush();
		session.close();
			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return false;
		 	}		

		 return true;
		
		
	}

	
	/**
	 * @param followerID
	 * @param followerId
	 */
	public boolean stopFollowing(int followerID, int followedID){
		///// need to find the one and then delete it!!!
		Log.info("Removing a friendship of users with ids : " +followerID + " , " +followedID);
				
		Follow follower=new Follow();
		
		try{
			Session session = sessionFactory.openSession();
			DBSessionManager manager = new DBSessionManager(session);
			
			Query query = session.createQuery("	from Follow as f " +
											  "	where f.followedId = " + followedID + 
											  " and f.followerId = " + followerID );
		
			@SuppressWarnings("unchecked")
			java.util.List<Follow> list = query.list();	
			Iterator<Follow> it=list.iterator();
			
			if (it.hasNext())
				follower=it.next();
			else return false;
			
		
			session.beginTransaction();
			
			//write the actions to do		
			manager.delete(follower);
			
			session.getTransaction().commit();
			session.flush();
			session.close();			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return false;
		 	}
		 
		return true;
	}

	@Override
	public boolean removeForum(int forumId) {
	///// need to find the one and then delete it!!!
		Log.debug("Trying to removing a forum with id : " +forumId);
		
		Forum forum=new Forum();
		
		try{
			Session session = sessionFactory.openSession();
			DBSessionManager manager = new DBSessionManager(session);
			
			Query query = session.createQuery("	from Forum as f " +
											  "	where f.forumId = " + forumId );
			 

			@SuppressWarnings("unchecked")
			java.util.List<Forum> list = query.list();	
			Iterator<Forum> it=list.iterator();
			
			if (it.hasNext())
				forum=it.next();
			else return false;
			
			forum.setDeleted(true);
		
			session.beginTransaction();
			
			//write the actions to do		
			manager.save(forum);
			
			session.getTransaction().commit();
			session.flush();
			session.close();
			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return false;
		 	}
		 
		 Log.info("Removed a forum with id : " +forumId);
	 
		return true;
	}

	@Override
	public boolean removeThread(int threadId) {
		///// need to find the one and then delete it!!!
		Log.debug("Trying to removing a thread with id : " +threadId);
		
		implementation.DB.DBreverse.Thread Thread=new implementation.DB.DBreverse.Thread();
		
		try{
			Session session = sessionFactory.openSession();
			DBSessionManager manager = new DBSessionManager(session);
			
			Query query = session.createQuery("	from Thread as t " +
											  "	where t.forumId = " + threadId );
		 

			@SuppressWarnings("unchecked")
			java.util.List<implementation.DB.DBreverse.Thread> list = query.list();	
			Iterator<implementation.DB.DBreverse.Thread> it=list.iterator();
			
			if (it.hasNext())
				Thread=it.next();
			else return false;
			
			Thread.setDeleted(true);
				
			session.beginTransaction();
			
			//write the actions to do		
			manager.save(Thread);
			   
			session.getTransaction().commit();
			session.flush();
			session.close();			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return false;
		 	}
		 
		 Log.info("Removed a thread with id : " +threadId);
		 
		return true;
	}
	
	
	@Override
	public boolean removePost(int postId) {
		///// need to find the one and then delete it!!!
		Log.debug("Trying to removing a post with id : " +postId);
		
		Post post=new Post();		
		
		try{
			Session session = sessionFactory.openSession();
			DBSessionManager manager = new DBSessionManager(session);
			
			Query query = session.createQuery("	from Post as p " +
											  "	where p.postId = " + postId );
	
		
			@SuppressWarnings("unchecked")
			java.util.List<Post> list = query.list();	
			Iterator<Post> it=list.iterator();
				
			if (it.hasNext())
				post=it.next();
			else return false;
			
			post.setDeleted(true);
				
			session.beginTransaction();
			
			//write the actions to do		
			manager.save(post);
			
			session.getTransaction().commit();
			session.flush();
			session.close();			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return false;
		 	}
		 
		Log.info("Removed a post with id : " + postId);
			
		 
		return true;
	}

	@Override
	public boolean editPost(int postID, String topic, String content) {
	///// need to find the one and then delete it!!!
		Log.debug("Trying to removing a post with id : " +postID);
		
		Post post=new Post();
		
		try{
			Session session = sessionFactory.openSession();
			DBSessionManager manager = new DBSessionManager(session);
			
			Query query = session.createQuery("	from Post as p " +
											  "	where p.postId = " + postID );
		 
		
			@SuppressWarnings("unchecked")
			java.util.List<Post> list = query.list();	
				Iterator<Post> it=list.iterator();
				
			if (it.hasNext())
				post=it.next();
			else return false;
			
			post.setPostTopic(topic);
			post.setPostContent(content);
				
			session.beginTransaction();
			
			//write the actions to do		
			manager.update(post);
			
			session.getTransaction().commit();
			session.flush();
			session.close();			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
			 return false;
		 	}
		 
		Log.info("Removed a post with id : " + postID);
		 
		return true;
	}

	

	public void deleteAllTabels(){
		delete("DELETE FROM Post" , "Post");
		delete("DELETE FROM Thread" , "Thread");
		delete("DELETE FROM Forum" , "Forum");	
		delete("DELETE FROM Follow" , "Follow");
		delete("DELETE FROM User" , "User");
		delete("DELETE FROM Forumproperties" , "Forumproperties");
	}
	
	private ArrayList<Integer> getFollowers(int userId){
		
		Log.debug("Getting Followers of User with id :" +userId);
		ArrayList<Integer> tFollowers=new ArrayList<Integer>();		
					
		Session session = sessionFactory.openSession();
		
		Query query = session.createQuery("select followerId from Follow as f where f.followedId = " + userId);
			
		try{	
			@SuppressWarnings("unchecked")
			java.util.List<Integer> list = query.list();	
			
			tFollowers=new ArrayList<Integer>(list);
			
			
		 	}			
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
	 	}
		 
		session.close();
		Log.info("Got " +tFollowers.size() + " Followers of User with id : " + userId );
		return tFollowers;
	}

	private ArrayList<Integer> getFollowees(int userId){
		
		Log.debug("Getting Followees of User with id :" +userId);
		ArrayList<Integer> tFollowees=new ArrayList<Integer>();	
			
		Session session = sessionFactory.openSession();
		
		Query query = session.createQuery("select followedId from Follow as f where f.followerId = " + userId);
		
		try{
			@SuppressWarnings("unchecked")
			java.util.List<Integer> list = query.list();	
			tFollowees=new ArrayList<Integer>(list);
			
			
		 	}			
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
	 	}
		
		session.close();	
		Log.info("Got " +tFollowees.size() + " Followees of User with id : " + userId );
		return tFollowees;
	}

	private void delete(String hql,String from) {
		
		try{
			
			Session session = sessionFactory.openSession();	
		
			session.beginTransaction();
			
			//write the actions to do	    
			Query query = session.createQuery(hql);
	  
		    int rowCount = query.executeUpdate();
		    System.out.println("Rows affected: " + rowCount);
	
		    //See the results of the update
		    query = session.createQuery("from " + from);
		    @SuppressWarnings("rawtypes")
			List results = query.list();            
	
		    displayPostList(results , from );
			
			session.getTransaction().commit();
			session.flush();
			session.close();
				 
		 	}
			 catch(org.hibernate.HibernateException e){
				 System.out.println("the problem is : " +e.getMessage());
			 	}				
	}
	
	
	private void displayPostList(List list , String Table ){
	    Iterator iter = list.iterator();
	    if (!iter.hasNext()){
	        System.out.println("No " + Table + " to display.");
	        return;
	    }
	}
	
	/**
	 * 
	 * @return the id stored in the DB if fails returns -1
	 */
	private int retriveIdFromDB(){

			Log.debug("trying to retrive Id From DB ");
			
			int id=0;
			
			
			Session session = sessionFactory.openSession();
			
			Query query = session.createQuery("select p.property from Forumproperties as p where p.propertyName='idCounter'");
			try{	
				@SuppressWarnings("unchecked")
				java.util.List<Integer> list = query.list();
				Iterator<Integer> it=list.iterator();
				if(it.hasNext()){					
					id=it.next();					
				}
				else updateIDInDB();						
			} 
			catch(org.hibernate.HibernateException e){
				Log.debug("ERROR - the problem is in retriveIdFromDB : " +e.getMessage());
				 return -1;
			 	}
			catch(java.util.NoSuchElementException e){
				Log.debug("Id counter is not intiated in the DB");
				 return -1;
				}
				
			session.close();			
			Log.debug("Retrived Id From DB , Id is : " + id);					
				return id;			
		}
	
	
	private void updateIDInDB() {		
		
		Log.debug("updating id counter in the the databse , id is: " + idCounter );

		
		Forumproperties tIdCounter=new Forumproperties();
		
		try{
		
		Session session = sessionFactory.openSession();	
		DBSessionManager manager = new DBSessionManager(session);
		
		//write changes here
		tIdCounter.setPropertyName("idCounter");
		tIdCounter.setProperty(idCounter);
		
		session.beginTransaction();
		
		//write the actions to do	
		
		Query query = session.createQuery("from Forumproperties as p where p.propertyName = 'idCounter'"   );
		
		@SuppressWarnings("unchecked")
		java.util.List<Forumproperties> list = query.list();
		Iterator<Forumproperties> it=list.iterator();

		if(it.hasNext()){
			tIdCounter=it.next();
			tIdCounter.setProperty(idCounter);
			manager.update(tIdCounter);
		}
		else {
			tIdCounter.setPropertyName("idCounter");
			tIdCounter.setProperty(idCounter);
			manager.save(tIdCounter);
		}
		
		session.getTransaction().commit();
		session.flush();
		session.close();
			 
	 	}
		 catch(org.hibernate.HibernateException e){
			 System.out.println("the problem is : " +e.getMessage());
		 	}		
		 
		Log.debug("updated id counter in the the databse , id is: " + idCounter );

	}
		


}
